/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;



namespace Oceanside
{
    public partial class CashMoneyBox : ModalWindow
    {
        /// <summary>
        /// 
        /// </summary>
        public static UserResponse LastResponse
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public static decimal TotalAmount
        {
            get;
            set;
        }

        public static decimal TotalCost
        {
            get;
            set;
        }

        public string ProductDescription
        {
            get;
            set;
        }

        bool lastPressWasMoneyNumber = false;


        public static bool DialogIsOpen
        {
            get;
            set;
        }

        private Stack<int> stackOfEnteredInts = new Stack<int>(10);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private double KeypressesToNumber()
        {
            double amount = 0;
            int len = stackOfEnteredInts.Count;
            Stack<int> poppedStack = new Stack<int>(stackOfEnteredInts.Count);
            for (int i = 0; i < len; i++)
            {
                int pop = stackOfEnteredInts.Pop();
                poppedStack.Push(pop);

                if (i < 2)
                {
                    double multiplier = Math.Pow(10, -(2 - i));
                    amount += pop * multiplier;
                }
                else if (i == 2)
                {
                    amount += pop;
                }
                else
                {
                    double divisor = Math.Pow(10, i - 2);
                    amount += pop * divisor;
                }
            }
            ///Now reload the stack                
            for (int i = 0; i < len; i++)
            {
                stackOfEnteredInts.Push(poppedStack.Pop());
            }
            return amount;
        }

        /// <summary>
        /// 
        /// </summary>
        public CashMoneyBox()
            : base()
        {
            DialogIsOpen = false;
            modalDialogIsOpen = false;
            CurrentlyOpenInstance = null;
            InitializeComponent();
            keypad.SetNumericKeyCallbackDel(new KeyPad.NumericKeyCallbackDelType(NumericKeyPressed_NOTHROW));
            keypad.SetClearKeyCallbackDel(new KeyPad.ClearCallbackDelType(ClearKeyPressed_NOTHROW));
            keypad.SetOkKeyCallbackDel(new KeyPad.OkCallbackDelType(OkKeyPressed_NOTHROW));

            button5.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button10.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button15.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button20.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button30.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button40.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button50.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            button100.MouseDown += new MouseButtonEventHandler(buttonMoney_MouseDown_NOTHROW);
            buttonExit.MouseDown += new MouseButtonEventHandler(buttonExit_MouseDown);
        }

        void buttonExit_MouseDown(object sender, MouseButtonEventArgs e)
        {
            LastResponse = UserResponse.EXIT;
            HideMe();
        }

#if _TESTMODE
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        public void KeyPadButtonDown(int key)
        {
            switch (key)
            {
                case 0:
                    keypad.button11.Down();
                    break;
                case 1:
                    keypad.button1.Down();
                    break;
                case 2:
                    keypad.button2.Down();
                    break;
                case 3:
                    keypad.button3.Down();
                    break;
                case 4:
                    keypad.button4.Down();
                    break;
                case 5:
                    keypad.button5.Down();
                    break;
                case 6:
                    keypad.button6.Down();
                    break;
                case 7:
                    keypad.button7.Down();
                    break;
                case 8:
                    keypad.button8.Down();
                    break;
                case 9:
                    keypad.button9.Down();
                    break;
                case 10:
                    keypad.buttonCl.Down();
                    break;
                case 12:
                    keypad.buttonOk.Down();
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        public void KeyPadButtonUp(int key)
        {
            switch (key)
            {
                case 0:
                    keypad.button11.Up();
                    break;
                case 1:
                    keypad.button1.Up();
                    break;
                case 2:
                    keypad.button2.Up();
                    break;
                case 3:
                    keypad.button3.Up();
                    break;
                case 4:
                    keypad.button4.Up();
                    break;
                case 5:
                    keypad.button5.Up();
                    break;
                case 6:
                    keypad.button6.Up();
                    break;
                case 7:
                    keypad.button7.Up();
                    break;
                case 8:
                    keypad.button8.Up();
                    break;
                case 9:
                    keypad.button9.Up();
                    break;
                case 10:
                    keypad.buttonCl.Up();
                    break;
                case 12:
                    keypad.buttonOk.Up();
                    break;
            }
        }
#endif

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="sender"></param>
        /// <param Name="e"></param>
        void buttonMoney_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                _userAcceptedDefaultAmount = false;
                ShineButton_124_124 sb = (ShineButton_124_124)sender;
                int intInput = 0;
                int.TryParse(sb.Tag.ToString(), out intInput);
                stackOfEnteredInts.Clear();
                lastPressWasMoneyNumber = true;
                switch (intInput)
                {
                    case 0:
                        TotalAmount = 0;
                        LastResponse = UserResponse.ENTER;
                        HideMe();
                        break;
                    case 5:
                        stackOfEnteredInts.Push(5);
                        break;
                    case 10:
                        stackOfEnteredInts.Push(1);
                        stackOfEnteredInts.Push(0);
                        break;
                    case 15:
                        stackOfEnteredInts.Push(1);
                        stackOfEnteredInts.Push(5);
                        break;
                    case 20:
                        stackOfEnteredInts.Push(2);
                        stackOfEnteredInts.Push(0);
                        break;
                    case 30:
                        stackOfEnteredInts.Push(3);
                        stackOfEnteredInts.Push(0);
                        break;
                    case 40:
                        stackOfEnteredInts.Push(4);
                        stackOfEnteredInts.Push(0);
                        break;
                    case 50:
                        stackOfEnteredInts.Push(5);
                        stackOfEnteredInts.Push(0);
                        break;
                    case 100:
                        stackOfEnteredInts.Push(1);
                        stackOfEnteredInts.Push(0);
                        stackOfEnteredInts.Push(0);
                        break;

                }
                stackOfEnteredInts.Push(0);
                stackOfEnteredInts.Push(0);

                if (IsTipOrClaimDrawerMode)
                {
                    tbTotalCost.Text = KeypressesToNumber().ToString("c");
                }
                else
                {
                    tbTendered.Text = KeypressesToNumber().ToString("c");
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CASHMONEY_MONEY_BUTTON_MOUSE_DOWN, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void HideMe()
        {
            CurrentlyOpenInstance = null;
            tbTotalCost.Text = "";
            tbTendered.Text = "";
            stackOfEnteredInts.Clear();
            lastPressWasMoneyNumber = false;
            this.Topmost = false;
            this.Hide();
            CurrentlyOpenInstance = null;
            Application.Current.MainWindow.Topmost = true;

            ModalDialogIsOpen = false;
            DialogIsOpen = false;
        }

        private static bool _userAcceptedDefaultAmount;


        public enum CashBoxType
        {
            TYPE_CLAIM_DRAWER,
            TYPE_PAYMENT,
            TYPE_TIPS,
            PAYIN_PAYOUT
        }

        /// <summary>
        /// 
        /// </summary>
        public void ShowMe(decimal baseAmount = 0M, CashBoxType type = CashMoneyBox.CashBoxType.TYPE_PAYMENT)
        {
            LastResponse = UserResponse.EXIT;
            TotalCost = baseAmount;

            currType = type;

            if (IsTipOrClaimDrawerMode)
            {
                if (type == CashBoxType.TYPE_TIPS)
                {
                    lblTotal.Content = "Cash Tips:";
                }
                else if (type == CashBoxType.PAYIN_PAYOUT)
                {
                    lblTotal.Content = "How Much:";
                }
                else
                {
                    lblTotal.Content = "Drawer Start:";
                }
                lblTender.Visibility = System.Windows.Visibility.Hidden;
                tbTendered.Visibility = System.Windows.Visibility.Hidden;
                tbTotalCost.IsEnabled = true;
                TotalCost = 0M;
                tbTotalCost.Text = TotalCost.ToString("c");
                tbTotalCost.Focus();
            }
            else
            {
                lblTotal.Content = "Cost:";
                _userAcceptedDefaultAmount = true;
                tbTotalCost.IsEnabled = false;
                tbTotalCost.Text = TotalCost.ToString("c");
                tbTendered.Text = TotalCost.ToString("c");
                tbTendered.Focus();
                lblTender.Visibility = System.Windows.Visibility.Visible;
                tbTendered.Visibility = System.Windows.Visibility.Visible;
            }

            TotalAmount = 0;
            CurrentlyOpenInstance = this;
            ModalDialogIsOpen = true;
            DialogIsOpen = true;
            this.Topmost = true;
            Application.Current.MainWindow.Topmost = false;
            this.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param Name="val"></param>
        private void NumericKeyPressed_NOTHROW(int val)
        {
            try
            {
                _userAcceptedDefaultAmount = false;

                if (lastPressWasMoneyNumber)
                {
                    stackOfEnteredInts.Clear();
                    lastPressWasMoneyNumber = false;
                }
                stackOfEnteredInts.Push(val);

                if (IsTipOrClaimDrawerMode)
                {
                    tbTotalCost.Text = KeypressesToNumber().ToString("c");
                }
                else
                {
                    tbTendered.Text = KeypressesToNumber().ToString("c");
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CASHMONEY_NUMERIC_PRESSED, exc);
            }
        }

        private CashBoxType currType;
        private bool IsTipOrClaimDrawerMode
        {
            get { return currType == CashBoxType.TYPE_CLAIM_DRAWER || currType == CashBoxType.TYPE_TIPS || currType == CashBoxType.PAYIN_PAYOUT; }
        }

        /// <summary>
        /// 
        /// </summary>
        public void ClearKeyPressed_NOTHROW()
        {
            try
            {
                if (IsTipOrClaimDrawerMode)
                {
                    tbTotalCost.Text = "";
                }
                else
                {
                    tbTendered.Text = "";
                }
                stackOfEnteredInts.Clear();
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CASHMONEY_CLEAR_PRESSED, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void OkKeyPressed_NOTHROW()
        {
            try
            {
                bool gotError = false;
                ///In this case the user simply accepted the default suggested payment amount that
                ///we set for them on the cash money box.
                if (_userAcceptedDefaultAmount)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(tbTendered.Text))
                        {
                            TotalAmount = 0;
                        }
                        else
                        {
                            TotalAmount = Decimal.Parse(tbTendered.Text.ToString(), System.Globalization.NumberStyles.Currency);
                        }
                    }
                    catch(Exception e)
                    {
                        Logging.LogException(e);
                    }
                }
                else
                {
                    TotalAmount = (decimal)KeypressesToNumber();
                }

                if (!gotError)
                {
                    LastResponse = UserResponse.ENTER;
                    HideMe();
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CASHMONEY_OK_PRESSED, exc);
            }
        }
    }
}
